package jp.gnt.mobion_foodnavi.utils;
import java.io.File;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

public class CameraUtils {
	public static final boolean ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY = false;

	/**
	 * Utility for taking picture from Camera app.
	 * 
	 * @return a valid Intent that we can start Camera app for taking photo.
	 */
	public static Intent startCameraToTakePhoto(Context context) {
		if (context == null)
			return null;
		Intent takePhotoIntent = null;
		takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				getUriCaptureTemp(context));
		System.out.println(">>>>>>>>> " + getUriCaptureTemp(context).toString());
		return takePhotoIntent;
	}

	public static File getFile(Context context, String filename) {
		if (ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY) {
			String path = context.getFilesDir().getPath() + filename;
			File file = new File(path);
			return file;
		} else {
			if (android.os.Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED)) {
				return new File(Environment.getExternalStorageDirectory(),
						filename);
			} else {
				return null;
			}
		}
	}

	private static Uri getUriCaptureTemp(Context context) {
		
		String temporaryName = String.format(Locale.getDefault(), "%d.jpeg",
				System.currentTimeMillis());
		
		File file = getFile(context, temporaryName);
		if (file != null) {
			return Uri.fromFile(file);
		}
		
		return null;
	}

	public static Intent getIntentCropImage(Uri uri, Context context) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setData(uri);
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		Uri tmpPath = CameraUtils.getUriCaptureTemp(context);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpPath);
		return intent;
	}
}
